Passed
Push — master ( 75553d...7a1003 )
by Rafael S.
01:46
created

riff.js ➔ getSubChunks   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
c 1
b 0
f 0
nc 2
dl 0
loc 17
rs 9.4285
nop 2
1
/*
2
 * riff
3
 * Get the chunks of a RIFF file.
4
 * TODO: This should be a npm package on its own.
5
 * Copyright (c) 2017 Rafael da Silva Rocha. MIT License.
6
 * https://github.com/rochars/wavefile
7
 *
8
 */
9
10
const byteData = require("byte-data");
11
12
/**
13
 * Get the chunks of a RIFF file.
14
 * @param {Uint8Array|!Array<number>} buffer the RIFF file bytes.
15
 * @param {boolean} bigEndian true if its RIFX.
16
 * @return {Object}
17
 */
18
function getChunks(buffer, bigEndian) {
19
    return {
20
        "chunkId": byteData.fromBytes(
21
                buffer.slice(0, 4), 8, {"char": true}
22
            ),
23
        "chunkSize": byteData.fromBytes(
24
                buffer.slice(4, 8), 32, {'be': bigEndian}
25
            )[0],
26
        "format": byteData.fromBytes(
27
                buffer.slice(8, 12), 8, {"char": true}
28
            ),
29
        "subChunks": getSubChunks(buffer, bigEndian)
30
    }
31
}
32
33
/**
34
 * List the sub chunks of a RIFF file.
35
 * @param {Uint8Array|!Array<number>} buffer the RIFF file bytes.
36
 * @param {boolean} bigEndian true if its RIFX.
37
 * @return {Object}
38
 */
39
function getSubChunks(buffer, bigEndian) {
40
    let chunks = [];
41
    let len = buffer.length;
42
    let i = 12;
43
    let subChunkSize;
44
    while(i < len) {
45
        subChunkSize = byteData.fromBytes(
46
            buffer.slice(i + 4, i + 8), 32, {'be': bigEndian})[0];
47
        chunks.push({
48
                "subChunkId": byteData.fromBytes(buffer.slice(i, i + 4), 8, {"char": true}),
49
                "subChunkSize": subChunkSize,
50
                "subChunkData": buffer.slice(i + 8, i + 8 + subChunkSize)
51
            });
52
        i = i + 8 + subChunkSize;
53
    }
54
    return chunks;
55
}
56
57
module.exports.getChunks = getChunks;
58